package com.anjiplus.template.gaea.auth.modules.thirdapis.service.impl;

import com.alibaba.fastjson.JSON;
import com.anji.plus.gaea.exception.BusinessExceptionBuilder;
import com.anjiplus.template.gaea.auth.modules.thirdapis.controller.param.AppspPushParam;
import com.anjiplus.template.gaea.auth.modules.thirdapis.dto.GaeaPushBatchDto;
import com.anjiplus.template.gaea.auth.modules.thirdapis.dto.GaeaPushInitDto;
import com.anjiplus.template.gaea.auth.modules.thirdapis.dto.PushMsgResponse;
import com.anjiplus.template.gaea.auth.modules.thirdapis.service.AppPushMsgService;
import com.anjiplus.template.gaea.auth.modules.user.dao.entity.GaeaUser;
import com.anjiplus.template.gaea.auth.modules.user.service.GaeaUserService;
import com.anjiplus.template.gaea.common.MagicValueConstants;
import com.anjiplus.template.gaea.common.RespCommonCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能描述：
 * app端推送服务
 * 需要调用推送平台接口
 *
 * @Author: peiyanni
 * @Date: 2021/4/6 10:08
 */
@Service
@RefreshScope
@Slf4j
public class AppPushMsgServiceImpl implements AppPushMsgService {

    @Resource(name = "authRestTemplate")
    private RestTemplate authRestTemplate;
    @Autowired
    private GaeaUserService gaeaUserService;

    @Value("${appsp.appKey:fb90cb5bc0c84a50883a3a2cc9295fbf}")
    String appKey;
    @Value("${appsp.secretKey:3cfeb0e9f5fd48fab00b4045a9da1f24}")
    String secretKey;
    @Value("${appsp.manuToken:}")
    String manuToken;
    @Value("${appsp.registrationId:}")
    String registrationId;
    @Value("${appsp.url:http://open-appsp.anji-plus.com}")
    String appspUrl;


    @Override
    public Boolean pushMsgInit(GaeaPushInitDto initDto) {
        initDto.setAppKey(appKey);
        String url = appspUrl + "/sp/push/init";
        String param = JSON.toJSONString(initDto);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("Accept", "application/json;charset=UTF-8");
        HttpEntity entity = new HttpEntity(param, headers);
        log.info("==Appsp推送服务初始化接口url={},请求参数：{}", url, param);
        String respJson = authRestTemplate.postForObject(url, entity, String.class);
        if (null == respJson) {
            return false;
        }
        log.info("---Appsp推送服务初始化返回结果---{}", respJson);
        PushMsgResponse pushMsgResponse=JSON.parseObject(respJson,PushMsgResponse.class);
        if ("0000".equals(pushMsgResponse.getRepCode())) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean pushMsgBatch(GaeaPushBatchDto batchDto) {
        if (!CollectionUtils.isEmpty(batchDto.getDeviceIds()) && batchDto.getDeviceIds().size() > MagicValueConstants.THOUSAND) {
            throw BusinessExceptionBuilder.build(RespCommonCode.DEVICEID_LENGTH);
        }
        batchDto.setAppKey(appKey);
        batchDto.setSecretKey(secretKey);
        String url = appspUrl + "/sp/push/pushBatch";
        String param = JSON.toJSONString(batchDto);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("Accept", "application/json;charset=UTF-8");
        HttpEntity entity = new HttpEntity(param, headers);
        log.info("==Appsp推送服务批量推送接口url={},请求参数：{}", url, param);
        String respJson = authRestTemplate.postForObject(url, entity, String.class);
        if (null == respJson) {
            return false;
        }
        log.info("---Appsp推送服务批量推送接口返回结果---{}", respJson);
        PushMsgResponse pushMsgResponse=JSON.parseObject(respJson,PushMsgResponse.class);
        if ("0000".equals(pushMsgResponse.getRepCode())) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean pushMsgAll(GaeaPushBatchDto allDto) {
        allDto.setAppKey(appKey);
        allDto.setSecretKey(secretKey);
        String url = appspUrl + "/sp/push/pushAll";
        String param = JSON.toJSONString(allDto);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("Accept", "application/json;charset=UTF-8");
        HttpEntity entity = new HttpEntity(param, headers);
        log.info("==Appsp推送服务全部推送接口url={},请求参数：{}", url, param);
        String respJson = authRestTemplate.postForObject(url, entity, String.class);
        if (null == respJson) {
            return false;
        }
        log.info("---Appsp推送服务全部推送接口返回结果---{}", respJson);
        PushMsgResponse pushMsgResponse=JSON.parseObject(respJson,PushMsgResponse.class);
        if ("0000".equals(pushMsgResponse.getRepCode())) {
            return true;
        }
        return false;

    }

    /**
     * 推送模板--app端测试发送
     * @param pushParam
     * @return
     */
    @Override
    public Boolean testPush(AppspPushParam pushParam) {
        List<GaeaUser> userList=gaeaUserService.getUserBynams(pushParam.getUsernames());
        if(CollectionUtils.isEmpty(userList)){
            log.info("---testpush --The user does not exist---");
            throw BusinessExceptionBuilder.build(RespCommonCode.USERINFO_EMPTY);
        }
        List<String> deviceIdList= userList.stream().filter(e-> !StringUtils.isEmpty(e.getDeviceId())).map(e->e.getDeviceId()).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(deviceIdList)){
            log.info("---testpush --user deviceId is null---");
            throw BusinessExceptionBuilder.build(RespCommonCode.USERINFO_EMPTY);
        }
        log.info("---testpush --user deviceId length-{}---",deviceIdList.size());
        GaeaPushBatchDto batchDto =new GaeaPushBatchDto();
        BeanUtils.copyProperties(pushParam,batchDto);
        batchDto.setDeviceIds(deviceIdList);
        return pushMsgBatch(batchDto);
    }

}
